import api from '@/api';
import { defineStore } from 'pinia';
import { useSceneStore } from '@/store/scene';
import { useStageStore } from '@/store/stage';
import { usePanelStore } from '@/store/panel';
import { messageUtil } from '@jl/element-plus/utils';

export const useEditorStore = defineStore('editor', () => {
  const route = useRoute();
  const sceneId = ref('');
  const sceneDetail = ref<API.Scene.Scene>({} as any);
  const sceneStore = useSceneStore(); // TODO 临时兼容旧版，重构后移除
  const stageStore = useStageStore();
  const panelStore = usePanelStore();
  // 默认为'' 鼠标样式 select: 选择, selectable: 可选择状态, unselectable: 不可选
  const mouseClass = ref('');
   /**
   * 全局变量
   */
   const globalVariables = ref<any[]>([]);

  // 初始化
  const init = async () => {
    // 设置场景id
    const id = route.params.id as string;
    sceneId.value = id;

    // 获取场景详情
    const result = await api.scene.getSceneDetail({ params: { activityId: id } });
    sceneDetail.value = result;
    sceneStore.sceneDetail = result; // TODO 临时兼容旧版，重构后移除
  };

  // 初始化
  const setSceneDetail = (data: any) => {
    sceneId.value = data.activityId;
    sceneDetail.value = data;
  };

  const saveScene = async (visible: boolean) => {
    const { cimInstance } = window;

    const cimupJson = cimInstance.api.exportCurrentScene();
    const configJson = {
      stage: {
        layers: stageStore.layers,
        mapObject: cimupJson?.mapObject,
        globalEffect: stageStore.globalEffect,
      },
      panel: {
        layers: panelStore.layers,
      },
    };
    const formData = new FormData();
    formData.append('activityId', sceneId.value);
    formData.append('configJson', JSON.stringify(configJson));
    const saveResult = await api.scene.saveSceneConfig({ data: formData });

    const { conifgId } = saveResult;
    const { activityId, projectId, activityName, actDesp, actCover, actViewAngle } =
      sceneDetail.value;
    const updateSceneFormData = new FormData();
    updateSceneFormData.append('activityId', activityId);
    updateSceneFormData.append('projectId', projectId);
    updateSceneFormData.append('activityName', activityName);
    updateSceneFormData.append('actDesp', actDesp);
    updateSceneFormData.append('actCover', actCover);
    updateSceneFormData.append('actViewAngle', actViewAngle);
    updateSceneFormData.append('conifgId', conifgId);
    await api.scene.updateScene({ data: updateSceneFormData });
    visible && messageUtil.success('保存成功');
    init();
  };

  return {
    sceneId,
    sceneDetail,
    init,
    mouseClass,
    globalVariables,
    saveScene,
    setSceneDetail,
  };
});
